import React, { useState, useEffect } from 'react';
import marked from 'marked'
import moment from 'moment';
import '../static/css/AddArticle.css'
import { Row, Col, Input, Select, Button, DatePicker, message } from 'antd'
import servicePath from '../config/apiUrl'
import { post, get } from '../config/http'

const { Option } = Select;
const { TextArea } = Input

function AddArticle(props) {

    // 文章id  如果是是0 表示新增文章  其他值 标识 修改
    const [articleId, setArticleId] = useState(0)
    const [articleContent, setArticleContent] = useState("");
    const [markdownContent, setMarkdownContent] = useState("");

    const [introducemd, setIntroducemd] = useState("");
    const [introducehtml, setIntroducehtml] = useState("");

    const [typeInfo, setTypeInfo] = useState([]) // 文章类别信息
    const [selectedType, setSelectType] = useState("请选择")

    const [articleTitle, setArticleTitle] = useState("")

    const [showDate, setShowDate] = useState() // 发布时间

    useEffect(() => {
        getTypeInfo()
        let tmpId = props.match.params.id
        if (tmpId) {
            setArticleId(tmpId)
            getArticleById(tmpId)
        }
    }, [])


    marked.setOptions({
        renderer: marked.Renderer(),
        gfm: true,
        pedantic: false,
        sanitize: false,
        tables: true,
        breaks: false,
        smartLists: true,
        smartypants: false,
    });

    const changeContent = (e) => {
        setArticleContent(e.target.value)
        let html = marked(e.target.value)
        setMarkdownContent(html)
    }

    const changeIntroduce = (e) => {
        setIntroducemd(e.target.value)
        let html = marked(e.target.value)
        setIntroducehtml(html)
    }
    // 获取文章
    const getArticleById = (id) => {
        get(servicePath.getArticleById + id).then(
            (res) => {
                if (res.code == 200) {

                    setArticleTitle(res.data[0].title)
                    setArticleContent(res.data[0].article_cointent)
                    let html = marked(res.data[0].article_cointent)
                    setMarkdownContent(html)
                    setIntroducemd(res.data[0].introduce)
                    let tmpInt = marked(res.data[0].introduce)
                    setIntroducehtml(tmpInt)
                    setShowDate(res.data[0].addTime)
                    setSelectType(res.data[0].typeName)
                }
            }
        )
    }

    //下拉选中
    const selectTypeHandler = (value) => {
        setSelectType(value)
    }

    // 获取文章类型
    const getTypeInfo = () => {
        get(servicePath.getTypeInfo).then((res) => {
            if (res.code == "200") {
                setTypeInfo(res.data)
            }
        })
    }

    //提交
    const saveArticle = () => {
        // markedContent()

        if (selectedType == '请选择类型') {
            message.error('必须选择文章类别')
            return false
        } else if (!articleTitle) {
            message.error('文章名称不能为空')
            return false
        } else if (!articleContent) {
            message.error('文章内容不能为空')
            return false
        } else if (!introducemd) {
            message.error('简介不能为空')
            return false
        } else if (!showDate) {
            message.error('发布日期不能为空')
            return false
        }
        let dataProps = {};

        dataProps.type_id = selectedType;
        dataProps.title = articleTitle;
        dataProps.article_cointent = articleContent;
        dataProps.introduce = introducemd;

        let datetext = showDate.replace('-', '/') //把字符串转换成时间戳
        dataProps.addTime = (new Date(datetext).getTime()) / 1000

        if (articleId == 0) {
            dataProps.view_count = Math.ceil(Math.random() * 100);
            post(servicePath.addArticle, dataProps).then(
                (res) => {
                    if (res.code == "200") {
                        setArticleId(res.insertId);
                        message.success('文章保存成功')
                    } else {
                        message.error('文章保存成功')
                    }
                }
            )
        } else {
            dataProps.id = articleId;
            post(servicePath.updateArticle, dataProps).then(
                (res) => {
                    if (res.code == "200") {
                        message.success('文章修改成功')
                    } else {
                        message.error('文章修改失败')
                    }
                }
            )
        }
    }

    return (
        <>
            <Row gutter={5} style={{ height: '100%' }}>
                <Col span={18}>
                    <Row gutter={10} >
                        <Col span={20}>
                            <Input
                                value={articleTitle}
                                placeholder="博客标题"
                                size="large"
                                onChange={e => { setArticleTitle(e.target.value) }} />
                        </Col>
                        <Col span={4}>
                            <Select value={selectedType} size="large" onChange={selectTypeHandler} className="select-box">
                                {
                                    typeInfo.map((item, index) => {
                                        return (<Option key={index} value={item.id}>{item.typeName}</Option>)
                                    })
                                }
                            </Select>
                        </Col>
                    </Row>
                    <Row gutter={10} className="row-height mat" >
                        <Col span={12} >
                            <TextArea
                                className="markdown-content"
                                placeholder="文章简介"
                                value={articleContent}
                                onChange={changeContent}
                                onPressEnter={changeContent} />
                        </Col>
                        <Col span={12}>
                            <div className="show-html"
                                dangerouslySetInnerHTML={{ __html: markdownContent }} >
                            </div>
                        </Col>
                    </Row>
                </Col>
                <Col span={6}>
                    <Row>
                        <Col span={24}>
                            {/* <Button size="large">暂存文章</Button> */}
                            <Button type="primary" size="large" onClick={saveArticle}>发布文章</Button>
                        </Col>
                        <Col span={24} className="mat">
                            <TextArea
                                rows={4}
                                placeholder="文章简介"
                                onChange={changeIntroduce}
                                onPressEnter={changeIntroduce}
                                value={introducemd} />

                            <div className="introduce-html mat"
                                dangerouslySetInnerHTML={{ __html: '文章简介：' + introducehtml }} ></div>
                        </Col>
                        <Col span={24}>
                            <div className="date-select">
                                <DatePicker
                                    value={moment(showDate)}
                                    format="YYYY-MM-DD"
                                    onChange={(date, dateString) => setShowDate(dateString)}
                                    placeholder="发布日期"
                                    size="large" />
                            </div>
                        </Col>
                        {/* <Col span={12}>
                            <div className="date-select">
                                <DatePicker
                                    placeholder="修改日期"
                                    size="large"
                                />
                            </div>
                        </Col> */}
                    </Row>
                </Col>
            </Row>
        </>
    )
}
export default AddArticle